package bom.service.impl.organization;


import bom.configuration.constant.SystemStaticConst;
import bom.configuration.util.JsonHelper;
import bom.configuration.util.PrivilegeUtil;
import bom.configuration.util.UserInfo;
import bom.dao.organization.UserAssociateRoleDao;
import bom.dao.organization.UserDao;
import bom.pojo.organization.User;
import bom.pojo.organization.UserAssociateRole;
import bom.pojo.organization.UserRole;
import bom.pojo.query.Page;
import bom.pojo.query.QueryUser;
import bom.service.i.organization.UserService;
import com.alibaba.druid.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.ParameterizedType;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: Fancyears·Maylos·Malvis
 * @Description:
 * @Date: Created in  2018/11/27 15:25
 * @Modified By:
 */
@Service("userService")
@Transactional(rollbackFor = {IllegalArgumentException.class})
@EnableTransactionManagement(proxyTargetClass = true)
public class UserServiceImpl implements UserService {
    @Autowired(required = false)
    private UserDao userDao;

    @Autowired(required = false)
    private UserAssociateRoleDao userAssociateRoleDao;

    /**
     * 分页查询组织架构底下的用户
     *
     * @param queryUser 查询条件
     */
    public Page findByGroupUserPage(QueryUser queryUser) {
        List<User> list = userDao.findGroupUserByPage(queryUser);
        int count = userDao.countGroupUser(queryUser);
        return new Page(list, count);
    }

    /**
     * 功能描述：实现增加用户
     *
     * @param entity 保存对象
     * @return
     * @throws Exception
     */
    @Override
    public boolean save(User entity) throws Exception {
//		organization.setAddress(organization.getProvince()+organization.getCity()+organization.getDistrict()+organization.getStreetAddress());
        //过滤前端密码
        if (!SystemStaticConst.ORIGINAL_PASSWORD.equals(entity.getPassword())) {
            entity.setPassword(SystemStaticConst.ORIGINAL_PASSWORD);//初始密码全部为123456
        }

        entity.setPassword(UserInfo.encode(entity.getPassword()));
        entity.setState("1");
        entity.packagingRoles(entity.getRoleArray());
        List<UserRole> userRoleList = entity.getRoles();
        entity.setGroupId(entity.getOrgGroup().getGroupId());
        boolean success = userDao.save(entity) > 0;
        if (success) {
            if (userRoleList.size() > 0) {
                for (UserRole userRole : userRoleList) {
                    userAssociateRoleDao.save(new UserAssociateRole(entity.getId(), userRole.getId()));
                }
            }
        }
        return success;
    }

    /**
     * 功能描述：实现更新用户
     *
     * @param entity 修改对象
     * @return
     * @throws Exception
     */
    @Override
    public boolean update(User entity) throws Exception {
        entity.packagingRoles(entity.getRoleArray());
        userAssociateRoleDao.removeUserRole(entity);
        if (entity.getRoles().size() > 0) {
            for (UserRole userRole : entity.getRoles()) {
                userAssociateRoleDao.save(new UserAssociateRole(entity.getId(), userRole.getId()));
            }
        }
        return userDao.update(entity) > 0 ? true : false;
    }

    /**
     * 功能描述：批量删除用户
     *
     * @param entityList
     * @return
     * @throws Exception
     */
    @Override
    public boolean removeBath(List<User> entityList) throws Exception {
        for (User user : entityList) {
            userAssociateRoleDao.removeUserRole(user);
        }
        return userDao.removeBath(entityList)>0?true:false;
    }

    /**
     * 功能描述：更新用户状态为可用或者不可用
     *
     * @param user
     * @return
     */
    public boolean userControl(User user) {
        return userDao.userControl(user) > 0;
    }

    /**
     * 功能描述：根据账号来获取用户信息
     *
     * @param login
     * @return
     */
    public User findByLogin(String login) {
        return userDao.findByLogin(login);
    }

    @Override
    public Map<String, Object> userContr(User entity) {
        Map<String, Object> result = new HashMap<String, Object>();
        User user = UserInfo.getUser();
        User loginUser = findByLogin(user.getLogin());
        if (StringUtils.isEmpty(entity.getState())) {
            result.put(SystemStaticConst.RESULT, SystemStaticConst.FAIL);
            result.put(SystemStaticConst.MSG, "非法参数！");
            return result;
        }
        User u = null;
        if (entity.getState().equals("1")) {//启用账户
            u = findByUserId(Long.valueOf(entity.getId()), "0");//系统中存在用户

        } else {//禁用账户
            u = findByUserId(Long.valueOf(entity.getId()), "1");//系统中存在用户
        }
        if (null == u) {
            result.put(SystemStaticConst.RESULT, SystemStaticConst.FAIL);
            result.put(SystemStaticConst.MSG, "用户不存在！");
            return result;
        }
        if ("dcproxy".equals(u.getLogin())) {
            result.put(SystemStaticConst.RESULT, SystemStaticConst.FAIL);
            result.put(SystemStaticConst.MSG, "dcproxy账号无法禁用！");
            return result;
        }
        if (!PrivilegeUtil.hasAdministratorPrivilege(loginUser)) {
            result.put(SystemStaticConst.RESULT, SystemStaticConst.FAIL);
            result.put(SystemStaticConst.MSG, "只有系统管理员权限账户才能禁用/启用员工账号！");
            return result;
        }
        if (userControl(entity)) {
            result.put(SystemStaticConst.RESULT, SystemStaticConst.SUCCESS);
            result.put(SystemStaticConst.MSG, "更新用户状态成功！");
//            result.put("organization",organization);
        } else {
            result.put(SystemStaticConst.RESULT, SystemStaticConst.FAIL);
            result.put(SystemStaticConst.MSG, "更新用户状态失败！");
        }
        return result;
    }

    /**
     * 根据id 获取用户信息
     *
     * @param id
     * @return
     */
    public User findByUserId(Long id, String state) {
        if (id == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("state", state);
        return userDao.findUserById(map);
    }

    @Override
    public User get(User entity) {
        return null;
    }

    @Override
    public Map<String, Object> saveUser(User entity) throws Exception {
        //新增用户时，初始密码全部为123456
        User user = UserInfo.getUser();
        User u = findByLogin(user.getLogin());
        if (!PrivilegeUtil.hasAdministratorPrivilege(u)) {
            Map<String, Object> map = new HashMap<>();
            map.put(SystemStaticConst.RESULT, SystemStaticConst.FAIL);
            map.put(SystemStaticConst.MSG, "只有系统管理员权限账户才能增加员工信息！");
        }
        boolean success = save(entity);
        Map<String, Object> result = new HashMap<>();
        if (success) {
            result.put(SystemStaticConst.RESULT, SystemStaticConst.SUCCESS);
            result.put(SystemStaticConst.MSG, "增加数据成功！");
        } else {
            result.put(SystemStaticConst.RESULT, SystemStaticConst.FAIL);
            result.put(SystemStaticConst.MSG, "增加数据失败！");
        }
        return result;
    }

    @Override
    public Map<String, Object> removeByBatch(String json) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        com.alibaba.fastjson.JSONArray array = com.alibaba.fastjson.JSONObject.parseArray(json);
        String login = "";
        for (int i = 0; i < array.size(); i++) {
            com.alibaba.fastjson.JSONObject object = array.getJSONObject(i);
            if (object.containsKey("login")) {
                login = object.getString("login");
                break;
            }
        }

        if (SystemStaticConst.DCPROXY.equals(login)) {
            result.put(SystemStaticConst.RESULT, SystemStaticConst.FAIL);
            result.put(SystemStaticConst.MSG, "无法删除" + SystemStaticConst.DCPROXY + "账户！");
            return result;
        }
        removeBath((List<User>) JsonHelper.toList(json, (Class<User>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]));
        result.put(SystemStaticConst.RESULT, SystemStaticConst.SUCCESS);
        result.put(SystemStaticConst.MSG, "删除数据成功！");
        return result;
    }
}